import datetime
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib.dates import DateFormatter, WeekdayLocator, MONDAY, MonthLocator
from sklearn import preprocessing

na_black_friday = ['2014-11-28',
                   '2015-11-27',
                   '2016-11-25',
                   '2017-11-24',
                   '2018-11-30']
na_labor_day = ['2014-09-01',
                '2015-09-07',
                '2016-09-05',
                '2017-09-04',
                '2018-09-03']
emea_kaizhaijie = ['2014-07-29',
                   '2015-07-18',
                   '2016-07-05',
                   '2017-06-26',
                   '2018-06-15']

emea_guerbangjie = ['2014-10-04',
                    '2015-09-24',
                    '2016-09-13',
                    '2017-09-02',
                    '2018-08-22']
prc_double11 = ['2014-11-11',
                '2015-11-11',
                '2016-11-11',
                '2017-11-11',
                '2018-11-11']
prc_chinesenewyear = ['2014-02-01',
                      '2015-02-18',
                      '2016-02-07',
                      '2017-01-28',
                      '2018-02-16']
india_diwali_start = ['2014-10-23',
                      '2015-11-11',
                      '2016-10-30',
                      '2017-10-18',
                      '2018-11-06']
india_diwali_end = ['2014-10-27',
                    '2015-11-15',
                    '2016-11-03',
                    '2017-10-22',
                    '2018-11-10']
# Create the data
# rs = np.random.RandomState(1979)
# x = rs.randn(500)
# g = np.tile(list("ABCDEFGHIJ"), 50)
# df = pd.DataFrame(dict(x=x, g=g))
# print(df)
# m = df.g.map(ord)
# print(m)
# pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
# g = sns.FacetGrid(df, row="g", hue="g", aspect=15, size=.5, palette=pal)
# g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)
# g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2)
# g.map(plt.axhline, y=0, lw=2, clip_on=False)
# # Define and use aa simple function to label the plot in axes coordinates
# def label(x, color, label):
#     ax = plt.gca()
#     ax.text(0, .2, label, fontweight="bold", color=color,
#             ha="left", va="center", transform=ax.transAxes)
#

df_feature = pd.read_csv('data/feature_conclusion.csv')
df_feature = df_feature[['feature_name', 'version', 'status']]

pd.set_option('display.height', 1000)
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
# print(df_feature.pivot(index='feature_name', columns='version', values='status'))
plt.rcParams.update({'figure.autolayout': True})
sns.heatmap(df_feature.pivot(index='feature_name', columns='version', values='status'))  # , annot=True
# plt.show()
plt.close()
# exit(0)

# g.map(label, "x")
#
# # Set the subplots to overlap
# g.fig.subplots_adjust(hspace=-.25)
#
# # Remove axes details that don't play will with overlap
# g.set_titles("")
# g.set(yticks=[])
# g.despine(bottom=True, left=True)
# plt.show()
#
# sns.set(color_codes=True)
# iris = sns.load_dataset("iris")
# species = iris.pop("species")
# g = sns.clustermap(iris)
# plt.show()


# y = np.random.randint(1, 100, 40)
# y = y.reshape((5, 8))
# df = pd.DataFrame(y, columns=[x for x in 'abcdefgh'])
# sns.heatmap(df, annot=True)
# plt.show()
# plt.close()


# --
# ----
# data import

data = [['320-15ISK', 'INDIA', 'AP'],
        ['110-15IBR', 'EET', 'EMEA'],
        ['320-15ISK', 'EET', 'EMEA'],
        ['Y520-15IKBN', 'EET', 'EMEA']]

s = 3
family_desc = data[s][0]
# sub_geo = data[s][1]  # [Warning!] NA will be overwrite to NaN in pandas.
# geo = data[s][2]

sub_geo = 'INDIA'
# geo = 'EMEA'
business_type = 'Consumer'  # 'Commercial'
# ------------------- start reading -------------------------------------------
df = pd.read_csv('D:/!Python/helloworld2/feature_data_20171113_1_2.csv')

values = {'geo': 'NA', 'sub_geo': 'NA', 'date': '1900-01-01', 'original_quantity': 1}
df = df.fillna(value=values)
df = df[['sub_geo', 'family_desc', 'geo', 'group_id', 'date', 'original_quantity', 'business_type']]

# zscore = lambda x: (x-x.mean())/x.std()
assert isinstance(df, pd.DataFrame)

# -- 分类 --
# df = df[df['geo'] == geo]
df = df[df['sub_geo'] == sub_geo]
df = df[df['business_type'] == business_type]

df['new_col'] = df['sub_geo'] + '@' + df['group_id'] + '@' + df['family_desc']

df = df[['new_col', 'date', 'original_quantity']]
df = df.drop_duplicates()
df = df.pivot('date', 'new_col', 'original_quantity')
df = df.fillna(0)

x = df.values  # returns aa numpy array
# ---------- 进行归一化处理 ----------------------
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
df_c = df.columns
df = pd.DataFrame(x_scaled, index=df.index.values, columns=df.columns)

df_s = df.stack()
df_s = df_s.groupby(df_s.index.get_level_values(0)).sum()
df_s_index_list = list(map(lambda xx: datetime.datetime.strptime(xx, '%Y-%m-%d'), df_s.index.values.tolist()))
df_s_values = df_s.values.tolist()

# -------------- 进行图像绘制 -----------------
f, (ax2, ax1) = plt.subplots(figsize=(10, 8), nrows=2)
ax1.plot(df_s_index_list, df_s_values)

for day in india_diwali_start:
    datetime_day = datetime.datetime.strptime(day, '%Y-%m-%d')
    ax1.axvline(datetime_day, label="1", color='black', linestyle="--")  # hold=None

for day in india_diwali_end:
    datetime_day = datetime.datetime.strptime(day, '%Y-%m-%d')
    ax1.axvline(datetime_day, label="1", color='red', linestyle="--")  # hold=None

ax1.axhline(0, label="1", color='green', linestyle="--")
# plt.axvline('2017-02-13', hold=None, label="1", color='black', linestyle="--")
# plt.axvline(['2017-12-04', '2017-11-06', '2017-02-13'], hold=None, label="1", color='black', linestyle="--")
# print(np.linspace(-20, 120, 1000))
# exit(0)
yearsFmt = DateFormatter('%Y-%m-%d')
# ax = plt.axes()
ax1.xaxis.set_major_locator(MonthLocator(interval=2))
ax1.xaxis.set_major_formatter(yearsFmt)  # 设置主要时间显示格式(日期类型的格式化)

ax1.xaxis.set_minor_locator(WeekdayLocator(MONDAY))  # 设置次要时间间隔!!!!! 成功
df_s_index_list.sort()
min_date = df_s_index_list[0]
max_date = df_s_index_list[len(df_s_index_list) - 1]
ax1.set(xlim=[min_date, max_date])


labels = ax1.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')  # 标签是竖着排、还是横着排、还是斜着排

# fig = plt.figure(1)
# fig.set_size_inches(20, 10)  # 10 for 1000 pixels
# plt.show()
# exit(0)
# plt.savefig('output/' + sub_geo + ".jpg")
# exit(0)
# print(type(df.stack()))

df = df.T

sns.heatmap(df, center=0, ax=ax2, cbar=False)  # , annot=True
# mngr = plt.get_current_fig_manager()
# mngr.window.setGeometry(50, 50, 1960, 640)
# plt.tight_layout()

# ax2.xaxis.set_major_locator(MonthLocator(interval=2))
# ax2.xaxis.set_major_formatter(yearsFmt)  # 设置主要时间显示格式(日期类型的格式化)
# ax2.xaxis.set_minor_locator(WeekdayLocator(MONDAY))  # 设置次要时间间隔!!!!! 成功

labels = ax2.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax2.set(xlabel='datetime', ylabel='family_subgeo',
        title='heat_map')
plt.show()
